import { config } from '../config/env.js'
import { APIError } from '../middleware/error.js'
import { retryWithBackoff } from '../utils/retry.js'

export interface GenerateImageResponse {
  success: boolean
  imageUrl: string
  error?: string
}

const PLACEHOLDER_IMAGE_URL = 'https://via.placeholder.com/1024x1024/98FB98/333333?text=Emotion+Visualization'

export async function generateImage(prompt: string): Promise<GenerateImageResponse> {
  try {
    // Check if API key is configured
    if (!config.imageApi.apiKey || config.imageApi.apiKey === 'your_image_api_key_here') {
      console.warn('Image API key not configured, returning placeholder');
      return {
        success: false,
        imageUrl: PLACEHOLDER_IMAGE_URL,
        error: 'Image API key not configured',
      };
    }

    const response = await retryWithBackoff(async () => {
      return await fetch(config.imageApi.endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${config.imageApi.apiKey}`,
      },
      body: JSON.stringify({
        prompt,
        n: 1,
        size: '1024x1024',
      }),
      signal: AbortSignal.timeout(config.api.timeout),
    })
    })

    if (!response.ok) {
      if (response.status === 429) {
        throw new APIError('Rate limit exceeded', 429, true)
      }
      throw new APIError(`Image API request failed: ${response.statusText}`, response.status, true)
    }

    const data = await response.json() as {
      data?: Array<{
        url?: string
      }>
    }

    const imageUrl = data.data?.[0]?.url
    if (!imageUrl) {
      throw new APIError('Invalid image API response format', 500, true)
    }

    return {
      success: true,
      imageUrl,
    }
  } catch (error) {
    // Return fallback image on any error
    const errorMessage = error instanceof Error ? error.message : 'Image generation failed'
    
    return {
      success: false,
      imageUrl: PLACEHOLDER_IMAGE_URL,
      error: errorMessage,
    }
  }
}
